import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Table} from 'antd';
import {TABLE, DATE_FORMAT, DATETIME_FORMAT} from '../constants';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {exceptionTransferStatus, problemSeverity, vehicleNature, replyForm, occurCondition, importInfo, exceptionInfoTransferApproveResult} from '../Enum';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {submitData, abandonData} from './api';
import styles from './style.css';
import routes from './routes';
const {Description} = DescriptionList;

export class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
    };
    componentDidMount() {
        this.props.init();
    }
    handleUpdateClick = () => {
        this.props.history.push(routes.update.format(this.props.id));
    }
    handleApproveClick = () => {
        this.props.history.push(routes.approve.format(this.props.id));
    }
    handleImproveResultClick = () => {
        this.props.history.push(routes.improveResult.format(this.props.id));
    }
    submitConfirm = () => {
        this.setState({loading: true});
        const rowVersion = this.props.detail.rowVersion;
        submitData(this.props.detail.id, rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    abandonConfirm = () => {
        this.setState({loading: true});
        const rowVersion = this.props.detail.rowVersion;
        abandonData(this.props.detail.id, rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    render() {
        const detailData = this.props.detail || {};
        const {options, details, confirmResult, improveResult} = detailData;
        const {isDealerUser} = this.props;
        const {formatMessage} = this.props.intl;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(options, PERMISSION.update))
            operations.push(<Button key="update" onClick={this.handleUpdateClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.edit',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(options, PERMISSION.submit))
            operations.push(
                <WrappedPopconfirm
                    id="submit"
                    key="submit"
                    title={formatMessage({
                        id: 'detailPanel.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    onConfirm={this.submitConfirm}>
                    <Button key="submit" size="small">{
                        formatMessage({
                            id: 'detailPanel.btn.submit',
                            defaultMessage: '提交'
                        })
                    }</Button>
                </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(options, PERMISSION.approve))
            operations.push(<Button key="approve" onClick={this.handleApproveClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.approve',
                    defaultMessage: '审核'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.improveResult) && hasPermissions(options, PERMISSION.improveResult))
            operations.push(<Button key="improveResult" onClick={this.handleImproveResultClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.improveResult',
                    defaultMessage: '改进结果登记'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(options, PERMISSION.abandon))
            operations.push(
                <WrappedPopconfirm
                    id="abandon"
                    key="abandon"
                    title={formatMessage({
                        id: 'detailPanel.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    onConfirm={this.abandonConfirm}>
                    <Button key="abandon" size="small">{
                        formatMessage({
                            id: 'detailPanel.btn.abandon',
                            defaultMessage: '作废'
                        })
                    }</Button>
                </WrappedPopconfirm>);
        const columns = [{
            title: formatMessage({
                id: 'detailPanel.column.vin',
                defaultMessage: 'VIN'
            }),
            dataIndex: 'vin',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.productCategoryCode',
                defaultMessage: '车型编号'
            }),
            dataIndex: 'productCategoryCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.productCategoryName',
                defaultMessage: '车型名称'
            }),
            dataIndex: 'productCategoryName',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.engineCode',
                defaultMessage: '发动机号'
            }),
            dataIndex: 'engineCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.transmissionSn',
                defaultMessage: '变速箱号'
            }),
            dataIndex: 'transmissionSn',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.productionDate',
                defaultMessage: '生产日期'
            }),
            dataIndex: 'productionDate',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.saleDate',
                defaultMessage: '购车日期'
            }),
            dataIndex: 'saleDate',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.faultDescription',
                defaultMessage: '故障描述'
            }),
            dataIndex: 'faultDescription',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.inspectionProcess',
                defaultMessage: '检查过程'
            }),
            dataIndex: 'inspectionProcess',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.dealResult',
                defaultMessage: '处理结果'
            }),
            dataIndex: 'dealResult',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.supplierCode',
                defaultMessage: '供应商代码'
            }),
            dataIndex: 'supplierCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.repairDate',
                defaultMessage: '修理日期'
            }),
            dataIndex: 'repairDate',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.mileage',
                defaultMessage: '行驶里程'
            }),
            dataIndex: 'mileage',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.claimPrice',
                defaultMessage: '索赔金额'
            }),
            dataIndex: 'claimPrice',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.subDealerCode',
                defaultMessage: '经销商编号'
            }),
            dataIndex: 'subDealerCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.subDealerName',
                defaultMessage: '经销商名称'
            }),
            dataIndex: 'subDealerName',
        }];
        const confirmResultColumns = [{
            title: formatMessage({
                id: 'detailPanel.column.confirmorName',
                defaultMessage: '审核人姓名'
            }),
            dataIndex: 'confirmorName',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.confirmTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'confirmTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.confirmComment',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'confirmComment',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approveResult',
                defaultMessage: '审核结果'
            }),
            dataIndex: 'approveResult',
            render: text => conventEnumValueToString(exceptionInfoTransferApproveResult, text)
        }];
        const improveResultColumns = [{
            title: formatMessage({
                id: 'detailPanel.column.registerName',
                defaultMessage: '登记人姓名'
            }),
            dataIndex: 'registerName',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.registerTime',
                defaultMessage: '登记时间'
            }),
            dataIndex: 'registerTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.improveSuggestion',
                defaultMessage: '改进建议或意见'
            }),
            dataIndex: 'improveSuggestion',
        }];
        return (
            <div className="detail">
                <Card loading={this.state.loading}>
                    <DescriptionList size="large" title={<Row><Col span={12}>{
                        formatMessage({
                            id: 'detailPanel.card.title',
                            defaultMessage: '质量反馈信息'
                        })
                    }</Col>
                    <Col className={`col-align-right ${styles.detail}`} span={12}>{operations}</Col>
                    </Row>}>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.code',
                            defaultMessage: '编号',
                        })}>{this.props.detail.code}</Description>
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.branchCode',
                            defaultMessage: '营销分公司编号',
                        })}>{this.props.detail.branchCode}</Description>}
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.branchName',
                            defaultMessage: '营销分公司名称',
                        })}>{this.props.detail.branchName}</Description>}
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.brandCode',
                            defaultMessage: '品牌编号',
                        })}>{this.props.detail.brandCode}</Description>}
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.brandName',
                            defaultMessage: '品牌名称',
                        })}>{this.props.detail.brandName}</Description>}
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.dealerCode',
                            defaultMessage: '总代编号',
                        })}>{this.props.detail.dealerCode}</Description>}
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.dealerName',
                            defaultMessage: '总代名称',
                        })}>{this.props.detail.dealerName}</Description>}
                        <Description term={formatMessage({
                            id: 'detailPanel.data.serviceEngineer',
                            defaultMessage: '售后服务工程师',
                        })}>{this.props.detail.serviceEngineer}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.qualityEngineer',
                            defaultMessage: '售后质量工程师',
                        })}>{this.props.detail.qualityEngineer}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.status',
                            defaultMessage: '状态'
                        })}>{conventEnumValueToString(exceptionTransferStatus, this.props.detail.status)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.productCategoryCode',
                            defaultMessage: '车型编号',
                        })}>{this.props.detail.productCategoryCode}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.productCategoryName',
                            defaultMessage: '车型名称',
                        })}>{this.props.detail.productCategoryName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.vehicleNature',
                            defaultMessage: '车辆性质'
                        })}>{conventEnumValueToString(vehicleNature, this.props.detail.vehicleNature)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.frequency',
                            defaultMessage: '频次',
                        })}>{this.props.detail.frequency}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.region',
                            defaultMessage: '区域',
                        })}>{this.props.detail.region}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.country',
                            defaultMessage: '国家',
                        })}>{this.props.detail.country}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.faultPartCode',
                            defaultMessage: '故障件代码',
                        })}>{this.props.detail.faultPartCode}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.customerComplainQty',
                            defaultMessage: '客户抱怨数',
                        })}>{this.props.detail.customerComplainQty}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.outRescueQty',
                            defaultMessage: '外出救援数',
                        })}>{this.props.detail.outRescueQty}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.specialCompensateQty',
                            defaultMessage: '客户特殊补偿数',
                        })}>{this.props.detail.specialCompensateQty}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.carReturnQty',
                            defaultMessage: '退换车数',
                        })}>{this.props.detail.carReturnQty}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.marketValueFactor',
                            defaultMessage: '市场评价系数',
                        })}>{this.props.detail.marketValueFactor}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.warranty',
                            defaultMessage: '索赔数',
                        })}>{this.props.detail.warranty}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.importInfo',
                            defaultMessage: '进口信息',
                        })}>{conventEnumValueToString(importInfo, this.props.detail.importInfo)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.causePartCode',
                            defaultMessage: '主损件编号',
                        })}>{this.props.detail.causePartCode}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.causePartName',
                            defaultMessage: '主损件名称',
                        })}>{this.props.detail.causePartName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.faultyPartBatch',
                            defaultMessage: '故障件生产批次',
                        })}>{this.props.detail.faultyPartBatch}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.softwareVersionNumber',
                            defaultMessage: '软件版本号',
                        })}>{this.props.detail.softwareVersionNumber}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.failureRatio',
                            defaultMessage: '故障比例',
                        })}>{this.props.detail.failureRatio}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.iPTV',
                            defaultMessage: 'IPTV',
                        })}>{this.props.detail.iPTV}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.occurCondition',
                            defaultMessage: '发生条件',
                        })}>{conventEnumValueToString(occurCondition, this.props.detail.occurCondition)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.issueRoadConditions',
                            defaultMessage: '问题出现路况',
                        })}>{this.props.detail.issueRoadConditions}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.issueWorkConditions',
                            defaultMessage: '问题出现工况',
                        })}>{this.props.detail.issueWorkConditions}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.driveHabits',
                            defaultMessage: '驾驶习惯',
                        })}>{this.props.detail.driveHabits}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.useEnvironment',
                            defaultMessage: '使用环境',
                        })}>{this.props.detail.useEnvironment}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.problemDescribe',
                            defaultMessage: '问题描述',
                        })}>{this.props.detail.problemDescribe}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.servicePropose',
                            defaultMessage: '服务站处理情况及建议',
                        })}>{this.props.detail.servicePropose}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.factoryAdvice',
                            defaultMessage: '工厂处理和建议',
                        })}>{this.props.detail.factoryAdvice}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.problemSeverity',
                            defaultMessage: '问题严重度',
                        })}>{conventEnumValueToString(problemSeverity, this.props.detail.problemSeverity)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.replyForm',
                            defaultMessage: '回复形式',
                        })}>{conventEnumValueToString(replyForm, this.props.detail.replyForm)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.creatorTime',
                            defaultMessage: '发起日期',
                        })}>{formatDateTime(this.props.detail.creatorTime, DATE_FORMAT)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.creatorName',
                            defaultMessage: '创建人姓名',
                        })}>{this.props.detail.creatorName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.modifierName',
                            defaultMessage: '修改人姓名',
                        })}>{this.props.detail.modifierName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.modifyTime',
                            defaultMessage: '修改时间',
                        })}>{formatDateTime(this.props.detail.modifyTime, DATETIME_FORMAT)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.submitterName',
                            defaultMessage: '提交人姓名',
                        })}>{this.props.detail.submitterName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.submitTime',
                            defaultMessage: '提交时间',
                        })}>{formatDateTime(this.props.detail.submitTime, DATETIME_FORMAT)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.abandonerName',
                            defaultMessage: '作废人姓名',
                        })}>{this.props.detail.abandonerName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.abandonTime',
                            defaultMessage: '作废时间',
                        })}>{formatDateTime(this.props.detail.abandonTime, DATETIME_FORMAT)}</Description>
                    </DescriptionList>
                </Card>
                <Card>
                    <DescriptionList title={formatMessage({
                        id: 'detailPanel.table.details',
                        defaultMessage: '质量反馈清单'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </DescriptionList>
                </Card>
                <Card>
                    <DescriptionList title={formatMessage({
                        id: 'detailPanel.table.confirmResultdetails',
                        defaultMessage: '审核结果清单'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            columns={confirmResultColumns}
                            rowKey="id"
                            pagination={false}
                            dataSource={confirmResult}
                            {...TABLE} />
                    </DescriptionList>
                </Card>
                <Card>
                    <DescriptionList title={formatMessage({
                        id: 'detailPanel.table.improveResultdetails',
                        defaultMessage: '改进结果清单'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            columns={improveResultColumns}
                            rowKey="id"
                            pagination={false}
                            dataSource={improveResult}
                            {...TABLE} />
                    </DescriptionList>
                </Card>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.state.loading}
                        onClick={this.props.onCancel}>{formatMessage({
                            id: 'detailPanel.btn.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    detail: PropTypes.object.isRequired,
    id: PropTypes.string.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    successReturn: PropTypes.func,
};

import {connect} from 'react-redux';
import {getDetail, tableSearch} from './actions';
import {injectIntl} from './intl';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);
const mapStateToProps = (state, props) => ({
    id: props.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    permissions: getPermissions(state),
    detail: getDetailData(state),
    isDealerUser: state.getIn(['page', 'domainData', 'init', 'isDealerUser']),
});
const mapDispatchToProps = (dispatch, props) => ({
    init: () => dispatch(getDetail(props.id)),
    onCancel: () => {
        props.history.push(routes.query.url());
    },
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
